<template>
  <el-form :inline="true" :model="queryForm" class="demo-form-inline">
    <el-form-item label="角色名:">
      <el-input
        v-model="queryForm.name"
        placeholder="请输入角色名"
        clearable
        style="width: 200px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
    </el-form-item>
  </el-form>

  <div class="table-header">
    <span class="table-title">角色列表</span>
    <el-button type="primary" @click="addRoleDialog = true" v-if="actions.includes('addRole')"
      >添加</el-button
    >
  </div>
  <el-table :data="tableData">
    <el-table-column prop="name" label="角色名" />
    <el-table-column prop="desc" label="描述" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button link type="primary" @click="openRolePermissionDialog(row.id)">
          权限设置</el-button
        >
        <el-button
          link
          type="primary"
          @click="openUpdateRoleDialog(row)"
          v-if="actions.includes('updateRole')"
          >编辑</el-button
        >
        <el-button
          link
          type="danger"
          @click="fetchDeleteRole(row.id)"
          v-if="actions.includes('delRole')"
        >
          删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
      v-if="page.total > 0"
      v-model:current-page="pageNumber"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40, 50]"
      :size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="addRoleDialog" title="添加角色" width="500">
    <el-form :model="addRoleForm">
      <el-form-item label="角色名" :label-width="formLabelWidth">
        <el-input v-model="addRoleForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="addRoleForm.desc" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchAddRole"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="updateRoleDialog" title="更新角色" width="500">
    <el-form :model="updateRoleForm">
      <el-form-item label="角色名" :label-width="formLabelWidth">
        <el-input v-model="updateRoleForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="desc" :label-width="formLabelWidth">
        <el-input v-model="updateRoleForm.desc" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateRoleDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchUpdateRole(updateRoleForm.id)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="setRolePermissionDialog" @close="drawer_close">
    <template #header><h4>权限设置</h4> </template>
    <template #default>
      <el-tree
        ref="rolePermissionTree"
        style="max-width: 600px"
        :data="treeData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :default-checked-keys="checked_node"
        :default-expand-all="true"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
    
    <script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import {
  listRole,
  createRole,
  deleteRole,
  updateRole,
  setRolePermission,
  listRolePermission
} from '@/api/role'
import { listMenuPermission } from '@/api/menu'
import { actions } from '@/api/auth'
import { ElMessage } from 'element-plus'
import { Delete, Edit } from '@element-plus/icons-vue'
import { id } from 'element-plus/es/locales.mjs'

const addRoleDialog = ref(false)
const updateRoleDialog = ref(false)
const setRolePermissionDialog = ref(false)
const formLabelWidth = '140px'
const page = reactive({ total: 0 })
const pageSize = ref(10)
const pageNumber = ref(1)
const rolePermissionTree = ref(null)
const checked_node = ref([])

const initAddRoleForm = reactive({
  name: '',
  desc: ''
  // 添加其他字段
})

//关闭抽屉时，销毁默认选中节点数据，不销毁这个数据，节点选中就不准确了
const drawer_close = () => {
  checked_node.value = []
}
const defaultProps = {
  children: 'children',
  label: 'name'
}

const addRoleForm = reactive({ ...initAddRoleForm })
const updateRoleForm = reactive({ ...initAddRoleForm })
const queryForm = reactive({ ...initAddRoleForm })
const selectedRoleId = ref(null)
const tableData = ref([])
const treeData = ref([])

// 定义一个方法来获取角色列表
const fetchListRole = async (params: {}) => {
  try {
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) => value !== undefined && value !== '')
    )
    const res = await listRole(filteredParams)
    tableData.value = res.data.data
    page.total = res.data.total
  } catch (error) {
    console.error('Failed to fetch user list:', error)
  }
}

const querySubmit = () => {
  pageNumber.value = 1
  fetchListRole({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}

const confirmClick = () => {
  if (rolePermissionTree.value) {
    // 获取选中的节点
    const checkedNodes = rolePermissionTree.value.getCheckedNodes()

    // 提取所有选中节点的权限
    const selectedPermissions = checkedNodes
      .map((node: any) => node.permissions)
      .filter((permissions: any) => permissions && permissions.length > 0) // 过滤掉没有权限的节点
      .flat() // 将数组拍平，得到一个权限列表
    if (selectedPermissions.length === 0) {
      ElMessage.error('请选择至少一个权限')
      return
    }

    // 假设 a 是当前选中的角色 ID，需传入正确的 role_id
    setRolePermission({ role_id: selectedRoleId.value, permission: selectedPermissions })
      .then(() => {
        ElMessage.success('角色权限绑定成功')
        setRolePermissionDialog.value = false // 关闭弹窗
      })
      .catch((error) => {
        console.error('Failed to set role permissions:', error)
        ElMessage.error('绑定角色权限失败')
      })
  } else {
    console.error('Tree instance not found')
  }
}

const openUpdateRoleDialog = (row: any) => {
  // Object.assign(updateUserForm, row)
  updateRoleForm.name = row.name
  updateRoleForm.desc = row.desc
  updateRoleForm.id = row.id // 需要确保 id 存在
  updateRoleDialog.value = true
}

const openRolePermissionDialog = async (row: any) => {
  setRolePermissionDialog.value = true
  selectedRoleId.value = row
  try {
    const res = await listRolePermission(row)
    // 递归处理树数据，自动勾选checked为true的节点
    const processTreeData = (data: any[]) => {
      return data.map((node) => {
        // 如果没有返回 `checked` 字段，默认设置为 `false`
        if (node.checked) {
          checked_node.value.push(node.id)
        }

        // 递归处理子节点
        if (node.children) {
          node.children = processTreeData(node.children)
        }
        return node
      })
    }
    // 设置树形数据并递归处理
    treeData.value = processTreeData(res.data.data)
  } catch (error) {
    console.error('Failed to fetch role permissions:', error)
  }
}

const fetchAddRole = async () => {
  try {
    const res = await createRole(addRoleForm)
    if (res.status < 300) {
      ElMessage.success('添加角色成功')
      addRoleDialog.value = false
      Object.assign(addRoleForm, initAddRoleForm) //重置表单内容，不然会显示上次的内容
      // 提交成功后刷新用户列表
      pageNumber.value = 1
      fetchListRole({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('添加角色失败')
    }
  } catch (error) {
    ElMessage.error('添加角色失败')
    console.error('Failed to add user:', error)
  }
}
// 定义一个方法来更新用户
const fetchUpdateRole = async (uuid: string) => {
  try {
    const res = await updateRole(uuid, updateRoleForm)
    if (res.status < 300) {
      ElMessage.success('更新角色成功')
      // 提交成功后刷新角色列表
      updateRoleDialog.value = false
      pageNumber.value = 1
      fetchListRole({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('更新角色失败')
    }
  } catch (error) {
    console.error('Failed to update user:', error)
  }
}

// 定义一个方法来删除角色
const fetchDeleteRole = async (id: string) => {
  try {
    const res = await deleteRole(id)
    if (res.status < 300) {
      ElMessage.success('删除角色成功')
      // 提交成功后刷新角色列表
      pageNumber.value = 1
      fetchListRole({
        page: pageNumber.value,
        size: pageSize.value,
        name: queryForm.name
      })
    } else {
      ElMessage.error('删除角色失败')
    }
  } catch (error) {
    ElMessage.error('删除角色失败')
    console.error('Failed to delete user:', error)
  }
}

// 使用 onMounted 在组件挂载后调用 fetchUserList 方法
onMounted(() => {
  fetchListRole({ page: pageNumber.value, size: pageSize.value })
})

const handleSizeChange = (size: number) => {
  pageSize.value = size
  pageNumber.value = 1 // 重置为第一页
  fetchListRole({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}

const handleCurrentChange = (page: number) => {
  pageNumber.value = page
  fetchListRole({
    page: pageNumber.value,
    size: pageSize.value,
    name: queryForm.name
  })
}
</script>
    
    <style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 25px; /* 添加顶部间距 */
}
.demo-form-inline {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}
</style>
    
    